# -*- coding: utf-8 -*-
# @Time : 2022/6/13 下午5:31
# @Author : wyf
# @FileName: 异步.py
# @Email: yunfei.wang@innvote.com

import asyncio
import time
import httpx
async def req(client, i):
    res = await client.get('https://www.baidu.com')
    print(f'第{i + 1}次请求，status_code = {res.status_code}')
    return res

async def main():
    async with httpx.AsyncClient() as client:
        task_list = []  # 任务列表
        for i in range(100):
            res = req(client, i)
            task = asyncio.create_task(res)  # 创建任务
            task_list.append(task)
        print("创建任务wanc")
        await asyncio.gather(*task_list)  # 收集任务

if __name__ == '__main__':
    start = time.time()
    asyncio.run(main())
    # loop = asyncio.get_event_loop()
    # result = loop.run_until_complete(main())
    # asyncio.get_event_loop().run_until_complete(main())
    end = time.time()
    print(f'异步发送100次请求，耗时：{end - start}')


# import time
# import httpx
#
# def main():
#     with httpx.Client() as client:
#         for i in range(100):
#             res = client.get('https://www.baidu.com')
#             print(f'第{i + 1}次请求，status_code = {res.status_code}')
#
# if __name__ == '__main__':
#     start = time.time()
#     main()
#     end = time.time()
#     print(f'同步发送100次请求，耗时：{end - start}')


